package com.hsy.swu.other.commentsection

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE
import androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_SETTLING
import com.google.android.material.internal.ViewUtils
import com.hsy.swu.clouddb.Comment
import com.hsy.swu.clouddb.LeanCloudHelper
import com.hsy.swu.databinding.OtherCommentBottomDialogBinding
import com.hsy.swu.hsyutils.HsyBottomSheetDialog
import com.hsy.swu.hsyutils.MActivityUtil
import com.hsy.swu.hsyutils.MLog

class CommentBottomDialog(context: Context) :
    HsyBottomSheetDialog<OtherCommentBottomDialogBinding>(context, {}) {
    private lateinit var mAdapter: CommentBottomDialogAdapter
    private lateinit var mLayoutManager: LinearLayoutManager

    @SuppressLint("RestrictedApi")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 默认有最高限制，高度太高划不到 rv最底部
        mBinding.root.layoutParams.height = ViewUtils.dpToPx(context, 700).toInt()

        setSendClick()
        setRvComment()

        mBinding.inputBar.visibility = View.GONE // 初始化变为 gone
        setOnDismissListener {
            mBinding.inputBar.visibility = View.GONE // 消失变为 gone
        }
    }

    override fun onStart() {
        super.onStart()

        setContentView(mBinding.root) // 因为可能获取管理员权限之前是 unusable，所以先设置 mBinding.root，再检测是否要显示 404

        /** 获取历史评论 */
        val commentList = mutableListOf<Comment>()
        LeanCloudHelper.getInstance()?.findObjectInBackground(
            "Comment",
            { /*it.orderByDescending("updatedAt")*/ }
        ) { lcObjectList ->
            MLog.v("comment list -> ${lcObjectList.size}")
            lcObjectList.forEach {
                // 遍历获取 comment并保存到 commentList
                commentList.add(
                    Comment(
                        it.getString("objectId"),
                        (it.getString("likeCounts") ?: "0").toInt(),
                        it.getString("likeUsers") ?: "",
                        it.getString("commentatorId"),
                        it.getString("commentatorNickName"),
                        it.getString("content"),
                        it.getString("createdAt"),
                        it.getString("updatedAt")
                    )
                )
            }
            mAdapter.mItemList = commentList
        }
    }

    /** 设置发送按钮点击事件 */
    @SuppressLint("NotifyDataSetChanged")
    private fun setSendClick() {
        mBinding.btnPostComment.setOnClickListener {
            mBinding.commentInput.apply {
                if (text.isNotEmpty()) {
                    LeanCloudHelper.getInstance()?.postComment(
                        text.toString(),
                        { MActivityUtil.showToast("评论失败，请稍后再试") }
                    ) {
                        setText("")
                        MActivityUtil.showToast("评论成功")
                        mAdapter.mItemList.add(
                            Comment(
                                it.getString("objectId"),
                                (it.getString("likeCounts") ?: "0").toInt(),
                                it.getString("likeUsers") ?: "",
                                it.getString("commentatorId"),
                                it.getString("commentatorNickName"),
                                it.getString("content"),
                                it.getString("createdAt")
                            )
                        )
                        mAdapter.apply {
                            notifyDataSetChanged()
                            mBinding.rvComment.smoothScrollToPosition(mItemList.size - 1)
                        }
                    }
                }
            }
        }
    }

    /** 向上和下翻页的 btn和滚动的处理 */
    private fun setRvComment() {
        mBinding.rvComment.apply {
            adapter = CommentBottomDialogAdapter().also {
                mAdapter = it
                it.setLikeClickListener { itemBinding, comment ->
                    when (itemBinding.like.progress) {
                        0f -> {
                            itemBinding.like.playAnimation()
                            LeanCloudHelper.getInstance()?.likeThisComment(
                                comment,
                                {
                                    itemBinding.like.cancelAnimation()
                                    itemBinding.like.progress = 0f
                                    MActivityUtil.showToast("点赞失败，请稍后再试")
                                }
                            ) {
                                comment.newLikeState = true
                                comment.newLikeCounts = comment.newLikeCounts!! + 1
                                itemBinding.likeCounts.text = "${comment.newLikeCounts!!}"
                                MActivityUtil.showToast("点赞成功")
                            }
                        }

                        1f -> {
                            itemBinding.like.progress = 0f
                            LeanCloudHelper.getInstance()?.cancelLikeThisComment(
                                comment,
                                {
                                    itemBinding.like.progress = 1f
                                    MActivityUtil.showToast("取消点赞失败，请稍后再试")
                                }
                            ) {
                                comment.newLikeState = false
                                comment.newLikeCounts = comment.newLikeCounts!! - 1
                                itemBinding.likeCounts.text = "${comment.newLikeCounts!!}"
                                MActivityUtil.showToast("取消点赞成功")
                            }
                        }
                    }
                }
            }

            layoutManager = LinearLayoutManager(context).apply {
                mLayoutManager = this
                reverseLayout = true
                stackFromEnd = true
            }

            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    when (newState) {
                        SCROLL_STATE_IDLE -> { // 空闲
                            if (mBinding.inputBar.visibility == View.GONE) {
                                MActivityUtil.scaleAnimOnShow(mBinding.inputBar)
                                mBinding.inputBar.visibility = View.VISIBLE
                            }

                            mBinding.btnPageUp.isClickable = true
                            mBinding.btnPageDown.isClickable = true

                            if (mLayoutManager.findLastCompletelyVisibleItemPosition() == mAdapter.mItemList.size - 1) {
                                // 划到最顶了
                                MActivityUtil.scaleAnimOnDismiss(mBinding.btnPageUp) {
                                    mBinding.btnPageUp.visibility = View.GONE
                                }
                            }

                            if (mLayoutManager.findFirstCompletelyVisibleItemPosition() == 0) {
                                // 划到最底了
                                MActivityUtil.scaleAnimOnDismiss(mBinding.btnPageDown) {
                                    mBinding.btnPageDown.visibility = View.GONE
                                }
                            }

                            if (mBinding.btnPageDown.visibility == View.GONE) {
                                MActivityUtil.scaleAnimOnShow(mBinding.btnPageDown)
                                mBinding.btnPageDown.visibility = View.VISIBLE
                                return
                            }


                            if (mBinding.btnPageUp.visibility == View.GONE) {
                                MActivityUtil.scaleAnimOnShow(mBinding.btnPageUp)
                                mBinding.btnPageUp.visibility = View.VISIBLE
                                return
                            }
                        }

                        SCROLL_STATE_SETTLING -> {
                            if (mBinding.inputBar.visibility == View.VISIBLE) {
                                MActivityUtil.scaleAnimOnDismiss(mBinding.inputBar) {
                                    mBinding.inputBar.visibility = View.GONE
                                }
                            }
                        }
                    }
                }
            })
        }

        mBinding.apply {
            btnPageUp.setOnClickListener {
                it.isClickable = false
                rvComment.smoothScrollToPosition(mLayoutManager.findLastCompletelyVisibleItemPosition() + 50)
            }

            btnPageDown.setOnClickListener {
                it.isClickable = false
                rvComment.smoothScrollToPosition(mLayoutManager.findLastCompletelyVisibleItemPosition() - 50)
            }
        }
    }
}